package com.ruoyi.user.service.impl;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.user.domain.UserChatRecord;
import com.ruoyi.user.domain.ChatSession;
import com.ruoyi.user.domain.MessageAttachment;
import com.ruoyi.user.mapper.UserChatRecordMapper;
import com.ruoyi.user.service.IUserChatRecordService;
import com.ruoyi.user.service.IUserAnnouncementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天记录Service业务层处理
 */
@Service
public class UserChatRecordServiceImpl implements IUserChatRecordService {
    @Autowired
    private UserChatRecordMapper userChatRecordMapper;

    @Autowired
    private IUserAnnouncementService userAnnouncementService;

    /**
     * 查询聊天记录
     */
    @Override
    public UserChatRecord selectUserChatRecordById(Long chatId) {
        return userChatRecordMapper.selectUserChatRecordById(chatId);
    }

    /**
     * 查询聊天记录列表
     */
    @Override
    public List<UserChatRecord> selectUserChatRecordList(UserChatRecord userChatRecord) {
        return userChatRecordMapper.selectUserChatRecordList(userChatRecord);
    }

    /**
     * 查询会话聊天记录
     */
    @Override
    public List<UserChatRecord> selectUserChatRecordsBySession(Long sessionId, Long customerId) {
        return userChatRecordMapper.selectUserChatRecordsBySession(sessionId, customerId);
    }

    /**
     * 查询用户会话列表
     */
    @Override
    public List<ChatSession> selectUserSessions(Long customerId) {
        return userChatRecordMapper.selectUserSessions(customerId);
    }

    /**
     * 查询会话信息
     */
    @Override
    public ChatSession selectSessionInfo(Long sessionId, Long customerId) {
        return userChatRecordMapper.selectSessionInfo(sessionId, customerId);
    }

    /**
     * 新增聊天记录
     */
    @Override
    public int insertUserChatRecord(UserChatRecord userChatRecord) {
        return userChatRecordMapper.insertUserChatRecord(userChatRecord);
    }

    /**
     * 修改聊天记录
     */
    @Override
    public int updateUserChatRecord(UserChatRecord userChatRecord) {
        return userChatRecordMapper.updateUserChatRecord(userChatRecord);
    }

    /**
     * 删除聊天记录
     */
    @Override
    public int deleteUserChatRecordById(Long chatId) {
        return userChatRecordMapper.deleteUserChatRecordById(chatId);
    }

    /**
     * 批量删除聊天记录
     */
    @Override
    public int deleteUserChatRecordByIds(Long[] chatIds) {
        return userChatRecordMapper.deleteUserChatRecordByIds(chatIds);
    }

    /**
     * 发送消息
     */
    @Override
    @Transactional
    public Map<String, Object> sendMessage(Long sessionId, Long customerId, String content,
                                           Integer messageType, MessageAttachment attachment,
                                           String relatedOrderId) {
        UserChatRecord userChatRecord = new UserChatRecord();
        userChatRecord.setSessionId(sessionId);
        userChatRecord.setCustomerId(customerId);
        userChatRecord.setContent(content);
        userChatRecord.setMessageType(messageType);
        userChatRecord.setIsRead(0); // 默认未读
        userChatRecord.setSentAt(new Date());
        userChatRecord.setSenderType(1); // 用户发送
        userChatRecord.setSenderId(customerId);

        if (attachment != null) {
            userChatRecord.setAttachments(JSON.toJSONString(attachment));
        }

        if (relatedOrderId != null) {
            try {
                userChatRecord.setRelatedOrderId(Long.valueOf(relatedOrderId));
            } catch (NumberFormatException e) {
                userChatRecord.setRelatedOrderId(null);
            }
        }

        // 根据会话ID获取聊天类型和目标ID
        ChatSession sessionInfo = selectSessionInfo(sessionId, customerId);
        if (sessionInfo != null) {
            // 会话存在，使用会话中的聊天类型
            userChatRecord.setChatType(sessionInfo.getChatType());
            if (sessionInfo.getChatType() == 1) {
                userChatRecord.setStaffId(sessionInfo.getTargetId());
            } else if (sessionInfo.getChatType() == 2) {
                userChatRecord.setMerchantId(sessionInfo.getTargetId());
            }
        } else {
            // 会话不存在，需要明确指定聊天类型
            // 这里需要根据业务逻辑确定聊天类型，假设是商家聊天
            userChatRecord.setChatType(2); // 2表示商家聊天
            // 需要从其他途径获取商家ID，比如从sessionId解析或者前端传递
            // 这里需要修改逻辑来获取正确的商家ID
            userChatRecord.setMerchantId(extractMerchantIdFromSession(sessionId));
        }

        int result = insertUserChatRecord(userChatRecord);

        Map<String, Object> response = new HashMap<>();
        if (result > 0) {
            response.put("chatId", userChatRecord.getChatId());
            response.put("sessionId", sessionId);
            response.put("content", content);
            response.put("messageType", messageType);
            response.put("attachments", attachment);
            response.put("isRead", 0);
            response.put("relatedOrderId", relatedOrderId);
            response.put("sentAt", userChatRecord.getSentAt());
        }

        return response;
    }

    // 新增方法：从sessionId中提取商家ID
    private Long extractMerchantIdFromSession(Long sessionId) {
        // 这里需要根据你的业务逻辑来实现
        // 例如：如果sessionId包含商家ID信息，可以从中提取
        // 或者查询其他表来获取
        // 暂时返回一个默认值，你需要根据实际情况修改
        return 1L; // 需要替换为实际的商家ID
    }

    /**
     * 标记消息为已读
     */
    @Override
    @Transactional
    public Map<String, Object> markMessagesAsRead(Long sessionId, Long customerId,
                                                Boolean readAll, List<Long> chatIds) {
        int readCount = userChatRecordMapper.markMessagesAsRead(sessionId, customerId,
                readAll != null && readAll ? null : chatIds);

        int unreadCount = selectUnreadCountBySession(sessionId, customerId);

        Map<String, Object> response = new HashMap<>();
        response.put("sessionId", sessionId);
        response.put("readCount", readCount);
        response.put("unreadCount", unreadCount);

        return response;
    }

    /**
     * 清空会话聊天记录
     */
    @Override
    @Transactional
    public Map<String, Object> clearSessionMessages(Long sessionId, Long customerId) {
        int deletedCount = userChatRecordMapper.clearSessionMessages(sessionId, customerId);

        Map<String, Object> response = new HashMap<>();
        response.put("sessionId", sessionId);
        response.put("deletedCount", deletedCount);

        return response;
    }

    /**
     * 查询会话未读消息数
     */
    @Override
    public int selectUnreadCountBySession(Long sessionId, Long customerId) {
        return userChatRecordMapper.selectUnreadCountBySession(sessionId, customerId);
    }

    /**
     * 查询用户总未读消息数
     */
    @Override
    public int selectTotalUnreadCount(Long customerId) {
        return userChatRecordMapper.selectTotalUnreadCount(customerId);
    }

    /**
     * 获取未读消息统计
     */
    @Override
    public Map<String, Object> getUnreadMessageStats(Long customerId) {
        // 获取用户区域ID（这里需要根据实际情况获取）
        Long regionId = getCurrentUserRegionId(customerId);

        Map<String, Object> stats = new HashMap<>();

        // 总未读消息数（聊天+通知）
        int chatUnreadCount = selectTotalUnreadCount(customerId);
        int notificationUnreadCount = userAnnouncementService.selectUnreadUserAnnouncementCount(customerId, regionId);
        stats.put("totalUnread", chatUnreadCount + notificationUnreadCount);

        // 各会话未读消息统计
        List<ChatSession> sessions = selectUserSessions(customerId);
        stats.put("sessions", sessions);

        // 未读通知数
        stats.put("notificationsUnread", notificationUnreadCount);

        return stats;
    }

    /**
     * 创建或获取会话
     */
    @Override
    public Long getOrCreateSession(Long customerId, Integer chatType, Long targetId) {
        // 先查询是否已存在会话
        List<ChatSession> userSessions = selectUserSessions(customerId);
        for (ChatSession session : userSessions) {
            if (session.getChatType().equals(chatType) && session.getTargetId().equals(targetId)) {
                return session.getSessionId();
            }
        }

        // 创建新会话 - 生成新的会话ID
        Long newSessionId = System.currentTimeMillis();
        
        // 创建一条初始消息
        UserChatRecord initialMessage = new UserChatRecord();
        initialMessage.setSessionId(newSessionId);
        initialMessage.setChatType(chatType);
        initialMessage.setCustomerId(customerId);
        initialMessage.setSenderType(4); // 系统
        initialMessage.setContent("会话已建立");
        initialMessage.setMessageType(5); // 系统通知
        initialMessage.setIsRead(1);
        initialMessage.setSentAt(new Date());
        
        if (chatType == 1) {
            initialMessage.setStaffId(targetId);
        } else if (chatType == 2) {
            initialMessage.setMerchantId(targetId);
        }
        
        insertUserChatRecord(initialMessage);
        
        return newSessionId;
    }

    /**
     * 获取当前用户区域ID（需要根据实际情况实现）
     */
    private Long getCurrentUserRegionId(Long customerId) {
        // 这里需要根据用户ID查询用户绑定的区域ID
        // 暂时返回默认区域ID 1
        return 1L;
    }
}